package com.ruoyi.prod.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.prod.entity.po.BaseLog;
import com.ruoyi.prod.enums.LogModuleEnum;
import com.ruoyi.prod.enums.LogTypeEnum;
import com.ruoyi.prod.enums.SysAction;
import com.ruoyi.prod.mapper.BaseLogMapper;
import com.ruoyi.prod.service.BaseLogService;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 基础管理-操作日志 服务实现类
 * </p>
 *
 * @author 强子初
 * @since 2023-02-18
 */
@Service
public class BaseLogServiceImpl extends ServiceImpl<BaseLogMapper, BaseLog> implements BaseLogService {

    @Override
    public List<BaseLog> list(BaseLog condition) {
        return this.list(this.getWrapper(condition));
    }

    @Override
    public Page<BaseLog> page(BaseLog condition) {
        Page<BaseLog> page = PageHelper.startPage(condition.getPageNum(), condition.getPageSize());
        this.list(condition);
        return page;
    }

    @Override
    public void save(String superId, LogModuleEnum module, LogTypeEnum type) {
        this.save(superId, module, type, null);
    }

    @Override
    public void save(String superId, LogModuleEnum module, LogTypeEnum type, String content) {
        BaseLog po = new BaseLog();
        po.setSuperId(superId);
        po.setModule(module);
        po.setType(type);
        po.setContent(content);
        this.saveOrUpdate(po);
    }

    @Override
    public void saveBatch(List<String> superIds, LogModuleEnum module, LogTypeEnum type) {
        this.saveBatch(superIds, module, type, null);
    }

    public void saveBatch(List<String> superIds, LogModuleEnum module, LogTypeEnum type, String content) {
        List<BaseLog> pos = new LinkedList<>();
        for (String superId : superIds) {
            BaseLog po = new BaseLog();
            po.setSuperId(superId);
            po.setModule(module);
            po.setType(type);
            po.setContent(content);
            pos.add(po);
        }
        this.saveBatch(pos);
    }

    private LambdaQueryWrapper<BaseLog> getWrapper(BaseLog condition) {
        LambdaQueryWrapper<BaseLog> wrapper = new LambdaQueryWrapper<>();

        // 模块
        if (condition.getModule() != null) wrapper.eq(BaseLog::getModule, condition.getModule());

        // 某一个确定的对象
        if (condition.getSuperId() != null) wrapper.eq(BaseLog::getSuperId, condition.getSuperId());

        // 开始时间
        if (condition.getStartDate() != null) wrapper.ge(BaseLog::getCreateTime, condition.getStartDate());

        // 结束时间
        if (condition.getEndDate() != null) wrapper.le(BaseLog::getCreateTime, condition.getEndDate());

        wrapper.orderByDesc(BaseLog::getCreateTime);
        return wrapper;
    }
}